import { director, instantiate, Node, Pool, Prefab, randomRangeInt, resources, SkeletalAnimationState, Animation } from "cc"
import { Actor } from "../actor/Actor"
import { Events } from "../events/Events"
import { EState } from "../actor/StateDefine"
import { EffectManager } from "./EffectManager"
import { DynamicResourceDefine } from "../resource/ResourceDefine"


export class ActorManager {
    //单例
    private static _instance: ActorManager = null
    public static get instance(): ActorManager {
        if (!this._instance) this._instance = new ActorManager()
        return this._instance
    }

    //主角
    playerActor: Actor = null

    enemies: Node[] = []

    enemyPool: Pool<Node> = null

    init(onComplete: () => void) {
        // 异步方法
        resources.loadDir("actor/enemy", Prefab, (err: Error, prefabs: Prefab[]) => {
            if (err) throw err
            this.enemyPool = new Pool<Node>((): Node => {
                let prefab = prefabs[randomRangeInt(0, prefabs.length)]
                let node = instantiate(prefab)
                director.getScene().addChild(node)
                return node
            }, prefabs.length, (node: Node) => {
                node.removeFromParent()
            })
            onComplete()
        })
    }
    destory() {
        this.enemyPool.destroy()
        this.enemies = []
    }
    createEnemy() {
        let node = this.enemyPool.alloc()
        node.active = true
        this.enemies.push(node)
        node.on(Events.OnDie, this.onEnemyDie, this)
        return node
    }
    onEnemyDie(node: Node) {
        const index = this.enemies.indexOf(node)
        this.enemies.splice(index, 1)

        let actor = node.getComponent(Actor)
        actor.skeletalAnimation.on(Animation.EventType.FINISHED, (type: Animation.EventType, state: SkeletalAnimationState) => {
            if (state.name === EState.Die) {
                this.enemyPool.free(node)
                node.active = false

                //死亡动画
                // EffectManager.instance.play(DynamicResourceDefine.EffDie, node.worldPosition)
            }
        })
    }

    public get randomEnemy() {
        return this.enemies[randomRangeInt(0, this.enemies.length)]
    }
}


